<template>
  <view class="payment-page">
    <!-- 支付信息 -->
    <view class="payment-info">
      <view class="amount-section">
        <text class="label">支付金额</text>
        <text class="amount">¥{{ amount }}</text>
      </view>
      <view class="order-section">
        <text class="label">订单编号</text>
        <text class="order-id">{{ orderId }}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-methods">
      <view class="section-title">选择支付方式</view>
      <view class="method-item" @tap="selectPayMethod('WECHAT_NATIVE')">
        <image src="/static/wxpay.png" mode="aspectFit" class="method-icon"></image>
        <text class="method-name">微信支付</text>
        <text class="method-selected">✓</text>
      </view>
    </view>

    <!-- 支付二维码 -->
    <view class="qrcode-popup-overlay" v-if="showQRCode">
      <view class="qrcode-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">使用微信扫码支付</text>
          <text class="close-btn" @click="cancelPayment">×</text>
        </view>
        <view class="qrcode-content">
          <view v-if="qrCodeUrl" class="qrcode-wrapper">
            <image 
              :src="qrCodeUrl" 
              mode="aspectFit" 
              class="qrcode-image"
              @error="handleQRCodeError"
              @load="handleQRCodeLoad"
            ></image>
            <text class="price">¥{{ amount }}</text>
          </view>
          <view v-else class="loading-wrapper">
            <text class="loading">正在生成支付二维码...</text>
          </view>
        </view>
        <view class="qrcode-footer">
          <text class="tip">请使用微信扫一扫完成支付</text>
          <text class="order-number">订单号：{{ orderId }}</text>
          <view class="qrcode-buttons">
            <button class="qr-btn cancel" @tap="cancelPayment">取消支付</button>
            <button class="qr-btn confirm" @tap="checkPaymentStatus">已完成支付</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-buttons">
      <button class="btn cancel" @tap="cancelPayment">取消支付</button>
      <button class="btn confirm" @tap="checkPaymentStatus">已完成支付</button>
    </view>
  </view>
</template>

<script>
import { orderMedicineApi } from '@/api/orderMedicine'

export default {
  data() {
    return {
      orderId: '',
      amount: '0.00',
      qrCodeUrl: '',
      showQRCode: false,
      paymentMethod: 'WECHAT_NATIVE',
      outTradeNo: '',
      paymentStatusTimer: null,
      checkCount: 0,
      maxChecks: 60 // 最多检查60次，3秒一次，共3分钟
    }
  },

  onLoad(options) {
    if (options.orderId && options.amount) {
      this.orderId = options.orderId
      this.amount = options.amount
      this.startPayment()
    } else {
      uni.showToast({
        title: '订单信息不完整',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },

  onUnload() {
    this.clearPaymentStatusCheck()
  },

  methods: {
    // 开始支付流程
    async startPayment() {
      try {
        uni.showLoading({
          title: '正在获取支付信息',
          mask: true
        })

        const params = {
          orderId: this.orderId,
          paymentType: this.paymentMethod,
          totalFee: Math.round(parseFloat(this.amount) * 100).toString(), // 转换为分
          userId: userId // 添加userId参数
        }

        const res = await orderMedicineApi.payOrder(params)
        
        if (res.code === 200 && res.data) {
          this.outTradeNo = res.data.outTradeNo
          this.qrCodeUrl = res.data.qrCodeImage
          this.showQRCode = true
          this.startPaymentStatusCheck()
        } else {
          throw new Error(res.msg || '获取支付二维码失败')
        }
      } catch (error) {
        console.error('发起支付失败:', error)
        uni.showToast({
          title: error.message || '支付失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 选择支付方式
    selectPayMethod(method) {
      this.paymentMethod = method
      this.startPayment()
    },

    // 开始检查支付状态
    startPaymentStatusCheck() {
      this.clearPaymentStatusCheck()
      this.checkCount = 0
      
      const checkStatus = async () => {
        try {
          this.checkCount++
          
          if (this.checkCount >= this.maxChecks) {
            this.handlePayTimeout()
            return
          }

          const res = await orderMedicineApi.checkPayStatus({
            orderId: this.orderId,
            outTradeNo: this.outTradeNo
          })

          if (res.code === 200) {
            const status = String(res.data).toUpperCase()
            switch(status) {
              case 'SUCCESS':
              case 'TRADE_SUCCESS':
                this.handlePaymentSuccess()
                return
              case 'FAIL':
              case 'TRADE_CLOSED':
                this.handlePaymentError()
                return
              case 'WAIT_BUYER_PAY':
              case 'NOTPAY':
              case 'USERPAYING':
                // 继续轮询
                break
              default:
                console.warn('未知的支付状态:', status)
                break
            }
          }
          
          this.paymentStatusTimer = setTimeout(checkStatus, 3000)
        } catch (error) {
          console.error('检查支付状态失败:', error)
          this.paymentStatusTimer = setTimeout(checkStatus, 3000)
        }
      }

      checkStatus()
    },

    // 清除支付状态检查
    clearPaymentStatusCheck() {
      if (this.paymentStatusTimer) {
        clearTimeout(this.paymentStatusTimer)
        this.paymentStatusTimer = null
      }
    },

    // 处理支付成功
    handlePaymentSuccess() {
      this.clearPaymentStatusCheck()
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      })
      
      setTimeout(() => {
        // 跳转到订单列表页
        uni.redirectTo({
          url: '/pages/order/order-list?status=PENDING_DELIVERY'
        })
      }, 1500)
    },

    // 处理支付超时
    handlePayTimeout() {
      this.clearPaymentStatusCheck()
      uni.showModal({
        title: '支付超时',
        content: '支付已超时，是否重新获取支付二维码？',
        success: (res) => {
          if (res.confirm) {
            this.startPayment()
          } else {
            this.cancelPayment()
          }
        }
      })
    },

    // 处理支付错误
    handlePaymentError() {
      this.clearPaymentStatusCheck()
      uni.showModal({
        title: '支付失败',
        content: '支付过程中出现错误，是否重试？',
        success: (res) => {
          if (res.confirm) {
            this.startPayment()
          } else {
            this.cancelPayment()
          }
        }
      })
    },

    // 添加二维码图片加载事件处理
    handleQRCodeLoad(event) {
      console.log('二维码图片加载成功:', event);
    },

    // 修改二维码加载错误处理方法
    handleQRCodeError(event) {
      console.error('二维码加载失败:', event);
      uni.showToast({
        title: '二维码加载失败，请重试',
        icon: 'none'
      });
      
      // 延迟后重新获取二维码
      setTimeout(() => {
        this.startPayment();
      }, 1500);
    },

    // 手动检查支付状态
    async checkPaymentStatus() {
      try {
        uni.showLoading({
          title: '正在查询支付结果',
          mask: true
        })

        const res = await orderMedicineApi.checkPayStatus({
          orderId: this.orderId,
          outTradeNo: this.outTradeNo
        })

        if (res.code === 200) {
          const status = String(res.data).toUpperCase()
          if (status === 'SUCCESS' || status === 'TRADE_SUCCESS') {
            this.handlePaymentSuccess()
          } else {
            uni.showToast({
              title: '支付未完成',
              icon: 'none'
            })
          }
        } else {
          throw new Error(res.msg || '查询支付状态失败')
        }
      } catch (error) {
        console.error('查询支付状态失败:', error)
        uni.showToast({
          title: error.message || '查询失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 取消支付
    cancelPayment() {
      uni.showModal({
        title: '提示',
        content: '确定要取消支付吗？',
        success: (res) => {
          if (res.confirm) {
            this.clearPaymentStatusCheck()
            // 跳转到订单列表页
            uni.redirectTo({
              url: '/pages/order/order-list?status=PENDING_PAYMENT'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.payment-page {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 30rpx;

  .payment-info {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;

    .amount-section {
      text-align: center;
      padding: 20rpx 0;
      margin-bottom: 20rpx;
      border-bottom: 1rpx solid #f5f5f5;

      .label {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
        display: block;
      }

      .amount {
        font-size: 48rpx;
        color: #ff5500;
        font-weight: bold;
      }
    }

    .order-section {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .label {
        font-size: 28rpx;
        color: #666;
      }

      .order-id {
        font-size: 28rpx;
        color: #333;
      }
    }
  }

  .payment-methods {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;

    .section-title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }

    .method-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;

      .method-icon {
        width: 48rpx;
        height: 48rpx;
        margin-right: 20rpx;
      }

      .method-name {
        flex: 1;
        font-size: 28rpx;
        color: #333;
      }

      .method-selected {
        font-size: 32rpx;
        color: #ff5500;
      }
    }
  }

  /* 更新二维码弹窗样式 */
  .qrcode-popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .qrcode-popup {
    background: #fff;
    border-radius: 12rpx;
    width: 600rpx;
    padding: 30rpx;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #eee;

      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .close-btn {
        font-size: 48rpx;
        color: #999;
        padding: 0 20rpx;
        line-height: 1;
        cursor: pointer;

        &:active {
          opacity: 0.7;
        }
      }
    }

    .qrcode-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20rpx 0;

      .qrcode-wrapper {
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .qrcode-image {
          width: 320rpx;
          height: 320rpx;
          background-color: #fff;
          border: 1px solid #eee;
          border-radius: 8rpx;
        }
        
        .price {
          margin-top: 20rpx;
          font-size: 36rpx;
          color: #ff4d4f;
          font-weight: bold;
        }
      }

      .loading-wrapper {
        height: 320rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .loading {
          font-size: 28rpx;
          color: #666;
        }
      }
    }

    .qrcode-footer {
      text-align: center;
      margin-top: 30rpx;
      
      .tip {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .order-number {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 20rpx;
      }

      .qrcode-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 30rpx;
        
        .qr-btn {
          width: 45%;
          height: 80rpx;
          line-height: 80rpx;
          border-radius: 40rpx;
          font-size: 28rpx;
          
          &.cancel {
            background-color: #f5f5f5;
            color: #666;
          }
          
          &.confirm {
            background-color: #ff5500;
            color: #fff;
          }
        }
      }
    }
  }

  .bottom-buttons {
    display: flex;
    justify-content: space-between;
    padding: 30rpx;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

    .btn {
      width: 45%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      font-size: 28rpx;

      &.cancel {
        background-color: #f5f5f5;
        color: #666;
      }

      &.confirm {
        background-color: #ff5500;
        color: #fff;
      }
    }
  }
}
</style> 